<template>
  <div class="viewCard">
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="波次号/容器号" required ref="myInput">
        <el-input v-model="form.wavePickingCode" :disabled='$store.state.retailers.isDisabled' id='inputId'
        @keydown.enter.native="waveNumberEnterDown()"
        @keyup.enter.native="waveNumberEnterUp()"
        ></el-input>
      </el-form-item>
      <el-form-item label="波次号">
        <span>{{state.form.wavePickingCode}}</span>
      </el-form-item>
      <el-form-item label="类型" >
        <span>{{state.form.orderTag}}</span>
      </el-form-item>
      <el-form-item label="入驻商" >
        <span>{{state.form.shipmentName}}</span>
      </el-form-item>
      <el-form-item label="承运商">
        <span>{{state.form.carrierName}}</span>
      </el-form-item>
      <el-form-item label="商品条码" required>
        <el-input
          id='goodsNo'
          v-model="form.no"
          @keydown.enter.native="courierNumberEnterDown()"
          @keyup.enter.native="courierNumberEnterUp()"></el-input>
      </el-form-item>
      <el-form-item label="商品名称">
        <span>{{state.goodsName}}</span>
      </el-form-item>
      <el-form-item label="复核数量">
         <el-input v-model="state.num" controls-position="right" id='refReunite' @keyup.enter.native='reunite'/>
      </el-form-item>
    </el-form>
    <el-table
      :align="allAlign"
      border
      :data="state.letData">
      <el-table-column  label="订单总数" align='center'>
        <template v-slot="{ row }">
           <span style="color:red;font-weight:700;font-size:18px">{{row.deliveryCount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="已复核" align='center'>
        <template v-slot="{ row }">
           <span style="color:green;font-weight:700;font-size:18px">{{row.recheckDeliveryCount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品总数" align='center'>
        <template v-slot="{ row }">
           <span style="color:red;font-weight:700;font-size:18px">{{row.planQuantity}}</span>
        </template>
      </el-table-column>
      <el-table-column  label="已复核" align='center'>
        <template v-slot="{ row }">
           <span style="color:green;font-weight:700;font-size:18px">{{row.recheckQuantity}}</span>
        </template>
      </el-table-column>
      <el-table-column  label="包裹数" align='center'>
        <template v-slot="{ row }">
           <span style="color:blue;font-weight:700;font-size:18px">{{row.deliveryCount}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="text green" v-if="state.complete">
        {{ state.form.wavePickingCode }}复核出库完成
    </div>
    <div class="text item" v-if="state.greater">
        复核数量大于商品总数量
    </div>
    <div class="text item" v-if="state.none">
        当前订单无此商品
    </div>
    <p> {{ state.cancelOrderPrompt }} </p>
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose">
      <div class="body">
        {{state.msg}}
      </div>
    </el-dialog>
  </div>
</template>

<script>
import soonPrint from '@/components/Printing/printBefore.js'
export default {
  name:'viewCard',
 data() {

    return {
      dialogVisible:false,
      waveNumberEnterDown(e){
        this.keyDownTimeWave = new Date().getTime();
      },
      waveNumberEnterUp(e){
        this.keyUpTimeWave = new Date().getTime();
        if(this.keyUpTimeWave - this.keyDownTimeWave < 30){
          if(this.len === 0){
            this.waveNumber()
            this.len = this.form.wavePickingCode.length
          }else{
            let lengths = this.form.wavePickingCode.length
            this.form.wavePickingCode = this.form.wavePickingCode.substring(this.len,lengths)
            this.waveNumber()
          }

        }else{
          this.waveNumber()
        }
      },
      state:this.$store.state.retailers,
      courierNumberEnterDown(e) {
        this.keyDownTime = new Date().getTime();
      },
      courierNumberEnterUp(e) {
        this.keyUpTime = new Date().getTime();
        if (this.keyUpTime - this.keyDownTime < 30) {
          if(!this.state.barCode){
            this.$store.commit('retailers/SET_NUM', '1')
            this.$store.commit('retailers/SET_SN', 0)
            this.$store.commit('retailers/SET_BARCODE',this.form.no )
            this.$store.dispatch("retailers/requestWaveNumber",this.form.wavePickingCode).then((res)=>{
              if(res === 3)return
              this.funForm()
              const rLoading = this.openLoading('复核中...')
              this.$store.dispatch('retailers/reunite',{val:1,noNum:this.noNum}).then(res=>{
                rLoading.close()
                if(res === 'err')return this.$message.error('商品条码不存在')
                if(res===9) return this.dialogVisible = true
                if(!res){
                  this.$store.commit('retailers/SET_NUM', '')
                  this.dialogVisible = false
                }else if(res === 1){
                  this.noNum = 1
                  // this.$store.commit('retailers/SET_FLAG',true)
                  localStorage.setItem('printData', JSON.stringify(this.$store.state.retailers.printData))
                  const routeUrl = this.$router.resolve({ path: '/printResult' })
                  // window.open(routeUrl.href, '_blank')
                  soonPrint(routeUrl.href)
                  // new PrintWaybill({ printData: this.$store.state.retailers.printData }).initSocket()
                }else if(res){
                  this.noNum = ++this.noNum
                }
              })
            })

          }else{
            let len = this.state.barCode.length
            let noLen = this.form.no.length
            this.form.no = this.form.no.substring(len,noLen)
            this.$store.commit('retailers/SET_NUM', '1')
            this.$store.commit('retailers/SET_SN', 0)
            this.$store.commit('retailers/SET_BARCODE',this.form.no )
            this.$store.dispatch("retailers/requestWaveNumber",this.form.wavePickingCode).then((res)=>{
              if(res === 'err')return this.$message.error('商品条码不存在')
              if(res === 3)return
              this.funForm()
              const rLoading = this.openLoading('复核中...')
              this.$store.dispatch('retailers/reunite',{val:1,noNum:this.noNum}).then(res=>{
                rLoading.close()
                if(res===9) return this.dialogVisible = true
                if(!res){
                  this.$store.commit('retailers/SET_NUM', '')
                  this.dialogVisible = false
                }else if(res === 1){
                  this.noNum = 1
                  // this.$store.commit('retailers/SET_FLAG',true)
                  // new PrintWaybill({ printData: this.$store.state.retailers.printData }).initSocket()
                  localStorage.setItem('printData', JSON.stringify(this.$store.state.retailers.printData))
                  const routeUrl = this.$router.resolve({ path: '/printResult' })
                  // window.open(routeUrl.href, '_blank')
                  soonPrint(routeUrl.href)
                }else if(res){
                  this.noNum = ++this.noNum
                }
              })
            })
          }
        } else {

          //直接按键盘触发
          this.$store.commit('retailers/SET_BARCODE',this.form.no )
          this.$store.commit('retailers/SET_NUM', '1')
          this.$store.commit('retailers/SET_SN', 1)
          this.$store.dispatch("retailers/requestWaveNumber",this.form.wavePickingCode).then((res)=>{
            document.getElementById('refReunite').focus()
            this.funForm()
          })
        }
      },
      allAlign:'center',
      form:{
        wavePickingCode:'',
        no:'',
        num:'',
      },
      len:0,
      start :new Date(),
      code:'',
      noNum:1,
      rules:{
        wavePickingCode:[
          { required: true, message: '请输入波次号/容器号', trigger: 'blur' }
        ],
        no:[
          { required: true, message: '请输入商品条码', trigger: 'blur' }
        ]
      },
    };
  },
  mounted () {
    document.getElementById('inputId').focus()
    this.$eventBus.$on('refreshCurrentPage', () => {
      this.state.complete && this.refreshCurrentPage()
    })
    this.$eventBus.$on('recheckReset', () => {
      this.courierNumberEnterUp()
    })
    // 当路由被 keep-alive 缓存时是不走 beforeDestroy 生命周期的，此时需要借助 activated 和 deactivated 这两个生命周期钩子
    // 页面销毁时解绑监听
    this.$on('hook:deactivated', () => {
      this.$eventBus.$off('recheckReset')
    })
  },
  methods: {
    // 复核完成 && 打印完成 后刷新当前页
    refreshCurrentPage() {
      this.$store.dispatch('tagsView/delCachedView', this.$route).then(() => {
        const { fullPath } = this.$route
        this.$nextTick(() => {
          this.$router.replace({
            path: '/redirect' + fullPath
          })
        })
      })
    },
    handleClose(){
      this.dialogVisible = false
    },
    // 波次号失去焦点
    waveNumber(){
      this.$store.dispatch("retailers/requestWaveNumber",this.form.wavePickingCode).then((res)=>{
        if(res === 3)return
        if(res === 1){
          this.$store.commit('retailers/SET_ISDISABLED', false)
          this.$store.commit('retailers/SET_COMPLETE',true)
        }else{
          document.getElementById('goodsNo').focus()
          this.$store.commit('retailers/SET_COMPLETE',false)
        }
      })
    },
    funForm(){
      this.$store.dispatch("retailers/barCode",this.form.no).then(res=>{
        if(!res){
          this.$message.error('请输入或扫描正确商品条码')
        }
      })
    },
    // 复核数量失去焦点
    reunite(){
      if(!this.form.no)return
      this.$store.commit('products/SET_SN', 1)
      if(!this.state.num)return this.$message.error('请输入复核数量')
      if(!Number(this.state.num)|| Number(this.state.num)<=0) return this.$message.error('请输入大于0的数字')
      const rLoading = this.openLoading('复核中...')
      this.$store.dispatch("retailers/reunite",{val:Number(this.state.num),noNum:this.noNum}).then(res=>{
        rLoading.close()
        if(res === 'err'){
          this.$message.error('当前订单无此商品')
          return rLoading.close()
        }
        if(res===9) return this.dialogVisible = true
        // document.getElementById('refReunite').blur()
        document.getElementById('goodsNo').focus()
        if(!res){
          this.$store.commit('retailers/SET_NUM', '')
          this.dialogVisible = false
        }else if(res === 1){
          this.noNum = 1
          // this.$store.commit('retailers/SET_FLAG',true)
          // new PrintWaybill({ printData: this.$store.state.retailers.printData }).initSocket()
          localStorage.setItem('printData', JSON.stringify(this.$store.state.retailers.printData))
          const routeUrl = this.$router.resolve({ path: '/printResult' })
          // window.open(routeUrl.href, '_blank')
          soonPrint(routeUrl.href)
        }else if(res){
          this.noNum = ++this.noNum
        }
      })

    },
  }
}
</script>

<style>
.body{
  text-align: left;
    width: 100%;
    word-wrap: break-word;
    color: red;
}
.green{
  background-color: rgb(99, 235, 99);
  height: 50px;
  line-height: 50px;
  text-align: center;
  margin-top: 5px;
  border-radius: 4px;
  font-size: 18px;
}
.item{
  background-color: red;
  height: 50px;
  line-height: 50px;
  text-align: center;
  margin-top: 5px;
  border-radius: 4px;
  font-size: 18px;
}
</style>
